const Router = require('koa-router')
const mongoose = require('mongoose')

let router = new Router()

router.get('/', async(ctx) => {
  ctx.body = '这是用户操作首页'
})

// 登录
router.post('/login', async(ctx) => {
  let loginUser = ctx.request.body
  console.log(loginUser)
  let userName = loginUser.userName
  let password = loginUser.password
  const User = mongoose.model('User')
  await User.findOne({ userName: userName }).exec()
    .then(async(result) => {
      console.log(result)
      if (result) {
        let newUser = new User()
        await newUser.comparePassword(password, result.password)
          .then((isMatch) => {
            if (isMatch) {
              ctx.body = { code: 200, message: isMatch }
            } else {
              ctx.body = { code: 201, message: '用户名或密码有误' }
            }
          })
          .catch(error => {
            console.log(err)
            ctx.body = { code: 500, message: error }
          })
      } else {
        ctx.body = { code: 201, message: '用户名不存在' }
      }
    })
    .catch(error => {
      console.log(error)
      ctx.body = { code: 500, message: error }
    })
})

// 注册
router.post('/register', async(ctx) => {
  console.log('ctx.request.body: ')
  console.log(ctx.request.body)
  // 取得model
  const User = mongoose.model('User')
  let newUser = new User(ctx.request.body)
  // 用mongoose的save方法直接存储，然后判断是否成功，返回相应的结果
  await newUser.save().then(() => {
    // 成功返回code=200，并返回成功信息
    ctx.body = {
      code: 200,
      message: '注册成功'
    }
  }).catch(error => {
    console.log(error)
    // 失败返回code=500，并返回错误信息
    ctx.body = {
      code: 500,
      message: error
    }
  })
  // ctx.body = '用户注册接口'
  console.log(ctx.request.body)
  // ctx.body = ctx.request.body
})

module.exports = router